package com.quanta.edaily.Service.impl;

import com.alibaba.fastjson.JSONObject;
import com.quanta.edaily.Service.UserService;
import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.bean.contants.ResultCode;
import com.quanta.edaily.config.exception.ServiceException;
import com.quanta.edaily.mapper.UserMapper;
import com.quanta.edaily.pojo.User;
import com.quanta.edaily.utils.RanUtils;
import com.quanta.edaily.utils.TokenUtils;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public JsonResponse loginByEDailyId(String edailyId, String password) {
        User user;
        try {
            user = userMapper.getUserByEDailyId(edailyId);
        } catch (Exception e) {
            log.error("业务异常", e);
            return JsonResponse.paramError("账号错误");
        }

        if (user == null) return JsonResponse.paramError("账户不存在");
        if (!Objects.equals(password, user.getPassword())) return JsonResponse.paramError("密码错误");

        String token = RanUtils.genToken(user.getId(), user.getPassword());
        userMapper.updateTokenById(user.getId(), token);
        JSONObject data = new JSONObject();
        data.put("id", user.getId());
        data.put("token", token);
        return JsonResponse.success("登录成功", data);
    }

    @Override
    public JsonResponse register(String name, String phone, String password) {
        User user, user2;
        try {
            user = userMapper.getUserByName(name);
            user2 = userMapper.getUserByPhone(phone);
        } catch (Exception e) {
            log.error("业务异常", e);
            return JsonResponse.paramError("参数错误");
        }
        if (user != null) return JsonResponse.paramError("用户名已被使用");
        if (user2 != null) return JsonResponse.paramError("手机号已被注册");
        user = new User();
        String ranNumStr = RanUtils.genNumStr(10);
        user.setEdailyId(ranNumStr);
        user.setName(name);
        user.setPhone(phone);
        user.setPassword(password);
        try {
            userMapper.insertUser(user);
        } catch (Exception e) {
            log.error("业务异常", e);
            return JsonResponse.paramError("参数错误");
        }
        JSONObject data = new JSONObject();
        data.put("user", user);
        return JsonResponse.success("注册成功", data);
    }

    @Override
    public JsonResponse updateUserById(User user){
        User user1 = TokenUtils.getCurrentUser();
        if (!user1.getId().equals(user.getId()))
            return JsonResponse.paramError("id有误");
        try {
            userMapper.updateUserById(user);
        } catch (Exception e) {
            throw new ServiceException(ResultCode.PARAM_ERROR, "参数错误");
        }
        return JsonResponse.success("更改成功");
    }

    @Override
    public JsonResponse findPage(int pageNum, int pageSize) {
        List<User> list = userMapper.findPage(pageNum, pageSize);
        JSONObject data = new JSONObject();
        data.put("total", countAllUser());
        data.put("userList", list);
        return JsonResponse.success("分页查询成功", data);
    }

    @Override
    public Integer countAllUser() {
        return userMapper.countAllUser();
    }

    @Override
    public JsonResponse deleteUserById(Integer id) {
        User user = TokenUtils.getCurrentUser();
        if (user == null || !Objects.equals(user.getId(), id))
            return JsonResponse.paramError("删除失败");
        userMapper.deleteUserById(id);
        return JsonResponse.success("删除成功");
    }

    @Override
    public JsonResponse updatePasswordById(Integer id, String op, String np) {
        int i = 0;
        User currentUser = TokenUtils.getCurrentUser();
        if (!currentUser.getId().equals(id))
            return JsonResponse.paramError("id错误");
        if(op==null || np==null|| np.equals(op))
            return JsonResponse.paramError("密码错误");
        try {
            i = userMapper.updatePasswordById(id, op, np);
        } catch (Exception e) {
            throw new ServiceException(ResultCode.PARAM_ERROR,"密码错误");
        }
        if (i != 1) return JsonResponse.systemError("密码错误");
        String token = RanUtils.genToken(id, np);
        userMapper.updateTokenById(id, token);
        JSONObject data = new JSONObject();
        data.put("token", token);
        return JsonResponse.success("更改成功", data);
    }

    @Override
    public JsonResponse getUserById(Integer id) {
        return JsonResponse.success("查询成功", userMapper.getUserById(id));
    }

    @Override
    public JsonResponse getAll() {
        return JsonResponse.success("查询成功", userMapper.getAll());
    }

    @Override
    public JsonResponse getPublished() {
        return JsonResponse.success("查询成功", userMapper.getPublished());
    }
}
